<template>
  <van-button
    :icon="value ? 'star' : 'star-o'"
    :class="{
      collected: value,
    }"
    :loading="loading"
    @click="onCollect"
  />
</template>

<script>
import { addCollect, deleteCollect } from "@/api/article";
export default {
  name: "CollectArticle",
  data() {
    return {
      loading: false,
    };
  },
  props: {
    value: {
      type: Boolean,
      required: true,
    },
    articleId: {
      type: [String, Number, Object],
      required: true,
    },
  },
  methods: {
    async onCollect() {
      this.loading = true;
      try {
        if (this.value) {
          // 已收藏，取消收藏
          await deleteCollect(this.articleId);
        } else {
          //没有收藏，添加收藏
          await addCollect(this.articleId);
        }
        //更新视图
        //自定义事件修改数据并不是立即的
        this.$emit("input", !this.value);
        this.$toast.success(this.value ? "取消收藏" : "收藏成功");
      } catch (err) {
        this.$toast("操作失败，请重试");
      }
      this.loading = false;
    },
  },
};
</script>

<style lang="less" scoped>
.collected {
  .van-icon {
    color: chocolate;
  }
}
</style>